package com.ericsson.entironment.manager;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ericsson.common.db.DatabaseMng;
import com.ericsson.common.exception.SmafException;
import com.ericsson.entironment.bean.HouseBean;
import com.ericsson.entironment.bean.LineDate;
import com.ericsson.entironment.bean.TerminalBean;
import com.ericsson.entironment.util.ResultCode;

public class TermManager
{	
	public static Log log=LogFactory.getLog(TermManager.class);
	public static boolean isSequenceExist(String seq)
	{
		Connection conn = null;
		Statement stmt = null;
		ResultSet rst = null;
		String sql="";
		try
		{
			conn = DatabaseMng.getInstance().getConnection();
			stmt = conn.createStatement();
			sql="select * from ema_terminal where trmSequence='"+seq+"'";
			rst=stmt.executeQuery(sql);
			if (rst.next())
			{//序列号存在
				return true;
			}
			//序列号不存在
			return false;
		}
		catch (Exception e)
		{
				
			log.error("execute sql error["+sql+"]",e);
			return false;
		}
		finally
		{
			try
			{
				if (rst != null)
					rst.close();
				if (stmt != null)
					stmt.close();
				if (conn != null)
					conn.close();
			}
			catch (Exception e)
			{

			}

		}
	}
	public static void setVip(String sequence)
	{
		Connection conn = null;
		Statement stmt = null;
		ResultSet rst = null;
		String sql = "";
		try
		{
			conn = DatabaseMng.getInstance().getConnection();
			stmt = conn.createStatement();
			sql="update ema_terminal set vip=0 where vip=1";
			stmt.executeUpdate(sql);
			sql="update ema_terminal set vip=1 where trmsequence='"+sequence+"'";
			stmt.executeUpdate(sql);

		}
		catch (Exception e)
		{
			log.error("execute sql error["+sql+"]",e);

		}
		finally
		{
			try
			{
				if (rst != null)
					rst.close();
				if (stmt != null)
					stmt.close();
				if (conn != null)
					conn.close();
			}
			catch (Exception e)
			{

			}

		}
	}
	
	/**
	 * 获取当前终端的曲线
	 * @return
	 */
	public static List getCurrentDate()
	{
		List lines=new ArrayList(); //曲线数据
		Connection conn = null;
		Statement stmt = null;
		ResultSet rst = null;
		String sql = "";
		long gm_8=28800000;//移动时区
		long offset=7200000;//每次显示前2个小时的数据
		long endtime=3600000;//结束时间，当前时间后推一小时
		long current;//当前时间
		List line=null; //每条线的数据
		String[] pot=null;//每个点的数据 
		String label="";
		LineDate lineDate=null;
		try
		{
			conn = DatabaseMng.getInstance().getConnection();
			stmt = conn.createStatement();
			//查找VIP终端
			sql="select * from ema_terminal where vip=1";
			rst=stmt.executeQuery(sql);
			if (rst.next())
			{//找到了Vip 终端，读取vip终端的曲线数据
				
				//取出当前时间
				current=(new Date()).getTime();
				//查找2小时前的数据
				sql="select * from ema_history where trmsequence='"+rst.getString("trmSequence")
					+"' and frametime>"+(current-offset)+" order by framename,frametime";
				rst=stmt.executeQuery(sql);
				while(rst.next())
				{
					if (label.equals(""))
					{//新的分类曲线
						label=rst.getString("framename");
						line=new ArrayList();
					}
					else
					{
						if (!label.equals(rst.getString("framename")))
						{//如果名字不相等，开始新的分类曲线，并保存原来的数据
							lineDate=new LineDate();
							lineDate.setLabel(label);
							lineDate.setData(line);
							lines.add(lineDate);//保存曲线内容到曲线序列中
							//开始新曲线
							label=rst.getString("framename");
							line=new ArrayList();
						}
					}
					//读取坐标点的值
					pot=new String[2];
					pot[0]=""+(rst.getLong("frametime")+gm_8);//时间轴
					pot[1]=rst.getString("framevalue");//采集值
					line.add(pot);
	
				}
				
				if (line!=null)
				{//有内容，可以生成最后一个点
					//循环结束，保存曲线
					//放入一个结束值
					pot=new String[2];
					pot[0]=""+(current+endtime+gm_8);//时间轴
					pot[1]=null;//采集值
					lineDate=new LineDate();
					line.add(pot);
					lineDate.setLabel(label);
					lineDate.setData(line);
					lines.add(lineDate);//保存曲线内容到曲线序列中
				}
			}

		}
		catch (Exception e)
		{
			log.error("execute sql error["+sql+"]",e);
		}
		finally
		{
			try
			{
				if (rst != null)
					rst.close();
				if (stmt != null)
					stmt.close();
				if (conn != null)
					conn.close();
			}
			catch (Exception e)
			{

			}

		}
		return lines;
	}
	public static List getTerminalConfig(String id)
	{//获取大棚终端的配置信息
		Connection conn = null;
		Statement stmt = null;
		ResultSet rst = null;
		String sql = "";
		List list=new ArrayList();
		try
		{
			conn = DatabaseMng.getInstance().getConnection();
			stmt = conn.createStatement();
			sql="select * from ema_valuelimit where trmsequence='"+id+"' order by frameid";
			rst=stmt.executeQuery(sql);
			while (rst.next())
			{
				list.add(rst.getString("framename"));
				list.add(rst.getString("tag"));
				list.add(rst.getString("framevalue"));
			}
			
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if (rst != null)
					rst.close();
				if (stmt != null)
					stmt.close();
				if (conn != null)
					conn.close();
			}
			catch (Exception e)
			{

			}

		}
		return list;
	}
	/**
	 * 获取当前大棚对应的终端
	 */
	public static List getTerminalList(String id)
	{
		Connection conn = null;
		Statement stmt = null;
		ResultSet rst = null;
		String sql = "";
		String options="";
		List record=new ArrayList();//保存要返回的记录
		List terminal=null;//保存终端的信息
		try
		{
			conn = DatabaseMng.getInstance().getConnection();
			stmt = conn.createStatement();
			//查找大棚安装了哪些终端
			sql="select * from ema_terminalinstall as rel,ema_terminal as term where rel.hsid='"+id+"' and term.trmSequence=rel.trmSequence";
			rst=stmt.executeQuery(sql);
			while(rst.next())
			{//将大棚信息加入记录
				terminal=new ArrayList();
				terminal.add(rst.getString("trmSequence"));
				terminal.add(rst.getString("trmname"));
				//获取传感器的最后一次值
				terminal.add(getLastValue(rst.getString("trmSequence")));
				//检查终端状态
				String status=checkTerminalStatus(rst.getString("trmSequence"));
				terminal.add(status);
				//操作选项
				//删除
				options="<a href='javascript:deleteTerminal(\""+rst.getString("trmSequence")+"\",\""+rst.getString("trmname")+"\")'><img src='./image/delete.gif' width=16 height=16 title='删除终端'></a>";
				//参数配置
				options+="&nbsp;&nbsp;<a href='javascript:configset(\""+rst.getString("trmSequence")+"\")'><img src='./image/configset.gif' width=16 height=16 title='参数配置'></a>";
				//远程激活
				if (status.indexOf("不在线")!=-1)
				{
					options+="&nbsp;&nbsp;<a href='javascript:doActive(\""+rst.getString("trmSequence")+"\")'><img src='./image/active.gif' width=16 height=16 title='远程激活'></a>";
				}
				//状态查询
				options+="&nbsp;&nbsp;<a href='javascript:configGet(\""+rst.getString("trmSequence")+"\")'><img src='./image/configget.gif' width=16 height=16 title='工作状态查询'></a>";
				
				
				terminal.add(options);
				
				record.add(terminal);
			}

		}
		catch (Exception e)
		{
			log.error("execute sql error["+sql+"]",e);
		}
		finally
		{
			try
			{
				if (rst != null)
					rst.close();
				if (stmt != null)
					stmt.close();
				if (conn != null)
					conn.close();
			}
			catch (Exception e)
			{

			}

		}
		return record;
	}
	public static String del(String seq)
	{
		TerminalBean terminal=new TerminalBean();
		terminal.load(seq);
		if (terminal.getTrmSequence()==null)
		{
			return "错误,您要删除的终端不存在";
		}
		try
		{
			terminal.delete();
		}
		catch (SmafException e)
		{
			return e.getMessage();
		}
		return "操作成功";
	}
	public static List getMsgDefines()
	{
		Connection conn = null;
		Statement stmt = null;
		ResultSet rst = null;
		String sql = "";
		int label=0;
		String intro="";
		List record=new ArrayList();
		List defines=new ArrayList();
		try
		{
			conn = DatabaseMng.getInstance().getConnection();
			stmt = conn.createStatement();
			sql="select * from ema_msgdefine order by msgdateid,frameid";
			rst=stmt.executeQuery(sql);
			while (rst.next())
			{
				if (label==0 || label!=rst.getInt("msgdateid"))
				{//新方案
					if (intro!="")
					{//方案说明
						defines.add(intro);
						record.add(defines);
					}
					defines=new ArrayList();
					defines.add("方案"+rst.getInt("msgdateid"));
					defines.add(rst.getInt("msgdateid"));
					label=rst.getInt("msgdateid");
					intro=""; 
				}
				intro+="["+rst.getInt("frameid")+":"+rst.getString("framename")+"]&nbsp;";
				
			}
			if (intro!="")
			{//方案说明
				defines.add(intro);
				record.add(defines);
			}

		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if (rst != null)
					rst.close();
				if (stmt != null)
					stmt.close();
				if (conn != null)
					conn.close();
			}
			catch (Exception e)
			{

			}

		}
		return record;
	}

	private static String checkTerminalStatus(String seq)
	{
		Connection conn = null;
		Statement stmt = null;
		ResultSet rst = null;
		String sql = "";
		long current;
		String result="";
		try
		{
			conn = DatabaseMng.getInstance().getConnection();
			stmt = conn.createStatement();
			//首先检查终端最后一次上报数据时间
			sql="select * from ema_terminal where trmsequence='"+seq+"'";
			rst=stmt.executeQuery(sql);
			if (rst.next())
			{
				current=(new Date()).getTime();
				if ((current-rst.getLong("lastmsgtime"))>300000)
				{//如果距离上次上报时间超过5分钟，终端处于不在线状态
					result="<img src='./image/offline.jpg' title='终端不在线'>";
				
				}
				else
				{//检查终端是否故障
					if (rst.getInt("trmstatus")==3)
					{//终端故障
						result="<img src='./image/workoff.jpg' title='终端故障'>";
				
					}
					else
					{//检查是否有告警
						if (rst.getInt("trmstatus")==2)
						{//终端告警
							result="<img src='./image/alert.jpg' title='"+rst.getString("alertcontent")+"'>";
							
						}
						else
						{//终端正常
							result="<img src='./image/online.jpg' title='正常工作'>";
						}
					}
				}
			}
			return result;

		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if (rst != null)
					rst.close();
				if (stmt != null)
					stmt.close();
				if (conn != null)
					conn.close();
			}
			catch (Exception e)
			{

			}

		}
		
		return null;
	}

	/**
	 * 获取最后一次传感器的采集值
	 * @param seq
	 * @return 0:采集值信息 1:状态信息
	 */
	private static String getLastValue(String seq)
	{
		Connection conn = null;
		Statement stmt = null;
		ResultSet rst = null;
		String sql = "";
		String result="";
		String label="";
		try
		{
			conn = DatabaseMng.getInstance().getConnection();
			stmt = conn.createStatement();
			sql="select * from ema_history where trmSequence='"+seq+"' order by frametime desc";
			rst=stmt.executeQuery(sql);
			 while(rst.next())
			{
				if (label.equals(""))
				{
					label=rst.getString("frametime");//保存最近的时间，用来判断是否已经取完所有的传感器值
				}
				
				if(!label.equals(rst.getString("frametime"))) 
				{//时间不一致，说明已经取出了所有传感器的值，返回
					return result;
				}
				else
				{
					//取出传感器值
					result+="&nbsp;&nbsp;"+rst.getString("framename")+":"+rst.getString("framevalue");
				}
			}

		}
		catch (Exception e)
		{
			log.error("execute sql error["+sql+"]",e);
		}
		finally
		{
			try
			{
				if (rst != null)
					rst.close();
				if (stmt != null)
					stmt.close();
				if (conn != null)
					conn.close();
			}
			catch (Exception e)
			{

			}

		}
		return null;
	}

	public static ResultCode saveNew(String hsid,String sequence, String name, String msgdefine)
	{
		ResultCode code=new ResultCode();
		//检查是否已经存在
		TerminalBean terminal=new TerminalBean();
		terminal.load(sequence);
		if (terminal.getTrmSequence()==null)
		{//大棚没有重名可以加入
			
			terminal.setTrmname(name);
			terminal.setTrmSequence(sequence);
			terminal.setMsgdateid(msgdefine);
			try
			{
				terminal.save(hsid);
			}
			catch (SmafException e)
			{
				code.setResult("failure");
				code.setMessage("系统错误，无法完成终端的新增");
				return code;
			}
			code.setResult("success");
		}
		else
		{
			code.setResult("failure");
			code.setMessage("终端序列号重复，请重新输入");
		}
		return code;
	}
}
